/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtpclient;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import com.googlecode.asyncmail.common.WiringContainer;
import com.googlecode.asyncmail.smtpserver.hook.MessageHook;

public final class BeanFactoryPostProcessorClass implements
        BeanFactoryPostProcessor {
    private MessageHook messageHook;

    public void postProcessBeanFactory(ConfigurableListableBeanFactory arg0)
            throws BeansException {
        arg0.addBeanPostProcessor(new BeanPostProcessor() {

            private MessageHook messageHook;

            public Object postProcessAfterInitialization(Object arg0,
                    String arg1) throws BeansException {
                return arg0;
            }

            public BeanPostProcessor setMessageHook(MessageHook messageHook) {
                this.messageHook = messageHook;
                return this;
            }

            public Object postProcessBeforeInitialization(Object arg0,
                    String arg1) throws BeansException {
                if ("hooksWiringContainer".equals(arg1)) {
                    ((WiringContainer) arg0).getHandlers().add(messageHook);
                }
                return arg0;
            }

        }.setMessageHook(messageHook));
    }

    public BeanFactoryPostProcessor setMessageHook(MessageHook messageHook) {
        this.messageHook = messageHook;
        return this;
    }
}